import random
import PyHook3
import tkinter
import tkinter.messagebox

stop = 0


class game2048():
    def __init__(self):
        self.row = 4
        self.col = 4
        self.cell = [[0 for i in range(0, 4)] for i in range(0, 4)]

    def load_data(self):
        print("--------------------------")
        for i in range(0, 4):
            for j in range(0, 4):
                print(str(self.cell[i][j]), end='  ')
            print()
        print("--------------------------")

    def move(self, direction):
        if (direction == "Up"):
            for i in range(0, 3):
                for j in range(0, 4):
                    if (self.cell[i][j] == self.cell[i + 1][j]):
                        self.cell[i][j] = self.cell[i][j] + self.cell[i + 1][j]
                        self.cell[i + 1][j] = 0
                    elif (self.cell[i][j] == 0):
                        self.cell[i][j] = self.cell[i + 1][j]
                        self.cell[i + 1][j] = 0
        elif (direction == "Down"):
            for i in range(3, 0, -1):
                for j in range(0, 4):
                    if (self.cell[i][j] == self.cell[i - 1][j]):
                        self.cell[i][j] = self.cell[i][j] + self.cell[i - 1][j]
                        self.cell[i - 1][j] = 0
                    elif (self.cell[i][j] == 0):
                        self.cell[i][j] = self.cell[i - 1][j]
                        self.cell[i - 1][j] = 0
        if (direction == "Left"):
            for i in range(0, 4):
                for j in range(0, 3):
                    if (self.cell[i][j] == self.cell[i][j + 1]):
                        self.cell[i][j] = self.cell[i][j] + self.cell[i][j + 1]
                        self.cell[i][j + 1] = 0
                    elif (self.cell[i][j] == 0):
                        self.cell[i][j] = self.cell[i][j + 1]
                        self.cell[i][j + 1] = 0
        elif (direction == "Right"):
            for i in range(0, 4):
                for j in range(3, 0, -1):
                    if (self.cell[i][j] == self.cell[i][j - 1]):
                        self.cell[i][j] = self.cell[i][j] + self.cell[i][j - 1]
                        self.cell[i][j - 1] = 0
                    elif (self.cell[i][j] == 0):
                        self.cell[i][j] = self.cell[i][j - 1]
                        self.cell[i][j - 1] = 0


class screen:
    def __init__(self, tk):
        self.tk = tk
        self.createscreen()
        self.data = game2048()
        # self.show_screen(self.data)
        self.hm = PyHook3.HookManager()
        self.hm.KeyDown = self.OnKeyboardEvent
        self.hm.HookKeyboard()

    def createscreen(self):
        self.button_list = []
        self.screen = tkinter.LabelFrame(self.tk)
        self.screen.grid(row=0, column=0, padx=4, pady=4, sticky="wesn")
        for i in range(16):
            button = tkinter.Button(self.screen, width=10, height=4)
            button.grid(row=i // 4, column=i % 4, padx=4, pady=4)
            self.button_list.append(button)
        self.tk.update()

    def update_status(self):
        mylist = []
        for i in range(0, 4):
            for j in range(0, 4):
                if (self.data.cell[i][j] == 0):
                    mylist.append(i * 4 + j)
        if mylist:
            n = random.choice(mylist)
            self.data.cell[n // 4][n % 4] = random.randrange(2, 5, 2)
            self.data.load_data()
            self.tk.update()
        else:
            m = 0
            global stop
            for i in range(0, 3):
                for j in range(0, 3):
                    if (self.data.cell[i][j] == self.data.cell[i + 1][j]):
                        m = m + 1
                    if (self.data.cell[i][j] == self.data.cell[i][j + 1]):
                        m = m + 1
            if (m == 0):
                print("Game over!")
                if (stop == 0):
                    stop = 1
                    self.hm.UnhookKeyboard()
                    tkinter.messagebox.showinfo('提示', '游戏结束')

    def show_data(self, data):
        for (i, button_item) in enumerate(self.button_list):
            button_item['text'] = data.cell[i // 4][i % 4]
            if (data.cell[i // 4][i % 4] < 64):
                button_item['fg'] = 'blue'
            elif (data.cell[i // 4][i % 4] < 512):
                button_item['fg'] = 'green'
            elif (data.cell[i // 4][i % 4] < 2048):
                button_item['fg'] = 'yellow'
            elif (data.cell[i // 4][i % 4] >= 2048):
                button_item['fg'] = 'red'
            else:
                button_item['fg'] = 'balck'
            if (int(button_item['text']) == 0):
                button_item['text'] = ''
        self.update_status()

    def OnKeyboardEvent(self, event):
        if (event.Key == "Up"):
            self.data.move("Up")
        elif (event.Key == "Down"):
            self.data.move("Down")
        elif (event.Key == "Left"):
            self.data.move("Left")
        elif (event.Key == "Right"):
            self.data.move("Right")
        else:
            return False
        self.show_data(self.data)
        return True


if __name__ == '__main__':
    game_tk = tkinter.Tk()
    game_tk.title("GAME_2048")
    game_screen = screen(game_tk)
    tkinter.messagebox.showinfo('提示', '游戏开始')
    import pythoncom
    pythoncom.PumpMessages()

